<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="provider" label="支付供应商">
        <uni-data-checkbox v-model="formData.provider" :localdata="formOptions.provider_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="status" label="订单状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="nickname" label="用户昵称">
        <uni-easyinput placeholder="用户昵称冗余" v-model="formData.nickname" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="支付描述">
        <uni-easyinput placeholder="支付描述，如：uniCloud个人版包月套餐" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="total_fee" label="订单总金额">
        <uni-easyinput placeholder="订单总金额，单位为分，100等于1元" type="number" v-model="formData.total_fee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="refund_fee" label="订单总退款金额">
        <uni-easyinput placeholder="订单总退款金额，单位为分，100等于1元" type="number" v-model="formData.refund_fee"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="user_order_success" label="回调状态">
        <switch @change="binddata('user_order_success', $event.detail.value)" :checked="formData.user_order_success"></switch>
      </uni-forms-item>
      <uni-forms-item name="custom" label="自定义数据">
        <undefined v-model="formData.custom"></undefined>
      </uni-forms-item>
      <uni-forms-item name="pay_date" label="支付时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.pay_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="cancel_date" label="取消时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.cancel_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="out_trade_no" label="支付插件订单号">
        <uni-easyinput placeholder="支付插件订单号（需控制唯一，不传则由插件自动生成）" v-model="formData.out_trade_no" trim="both"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/uni-pay-orders.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'uni-pay-orders';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "provider": "",
        "status": 0,
        "nickname": "",
        "description": "",
        "total_fee": null,
        "refund_fee": null,
        "user_order_success": null,
        "custom": null,
        "pay_date": null,
        "cancel_date": null,
        "out_trade_no": ""
      }
      return {
        formData,
        formOptions: {
          "provider_localdata": [
            {
              "text": "微信支付",
              "value": "wxpay"
            },
            {
              "text": "支付宝",
              "value": "alipay"
            },
            {
              "text": "苹果应用内支付",
              "value": "appleiap"
            }
          ],
          "status_localdata": [
            {
              "text": "已关闭",
              "value": -1
            },
            {
              "text": "未支付",
              "value": 0
            },
            {
              "text": "已支付",
              "value": 1
            },
            {
              "text": "已部分退款",
              "value": 2
            },
            {
              "text": "已全额退款",
              "value": 3
            },
            {
              "text": "退款中",
              "value": 4
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
